package com.yhcrt.controller;

import java.net.HttpURLConnection;
import java.util.*;
import java.util.stream.Collectors;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;

import com.sun.org.apache.bcel.internal.generic.CALOAD;
import com.yhcrt.entiy.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yhcrt.service.CommonService;
import com.yhcrt.service.MatchService;
import com.yhcrt.utils.Constants;
import com.yhcrt.utils.DateUtil;
import com.yhcrt.utils.JsonUtils;
import com.yhcrt.utils.RequestParam;
import com.yhcrt.utils.StringUtils;


/**
 * 
 * 公共业务处理器(无需权限)
 * @author fk
 * 2021年10月14日 上午15:44:30
 */
@Controller
public class CommonController {
	@Autowired
	private CommonService commonService;
	@Autowired
	private MatchService matchService;

	@Value("${opening.date}")
	private String opendingdate;   //开幕式日期
	@Value("${closing.date}")
	private String closingdate;    //闭幕式日期
	
	protected Map<String, Object> model = new LinkedHashMap<String, Object>();
	
	
	/**************************************首页**************************************************/
	@RequestMapping("/")
	@SuppressWarnings("all")
	public ModelAndView index(ModelMap modelMap){
		try{
			List<Map<String,String>> dataList = this.commonService.loadProjectList(Constants.matchId);
			System.out.println("========加载项目常量条数========" + dataList.size());
			Constants.PROJ_CODE2NAME_MAP = dataList.stream().filter(b->b.get("classCode")!=null && b.get("projectName")!=null).collect(Collectors.toMap(b->b.get("classCode"), b->b.get("projectName"), (oldVal, newVal)->oldVal));
		}catch (Exception e) {
			System.out.println("加载项目常量时：" + e.getMessage());
		}
		//获取竞赛的起止日期
		List<String> dateList = commonService.getDateList(Constants.matchId,Constants.QSN_ID);
		if(!dateList.contains(opendingdate)){
			dateList.add(opendingdate);
		}
		if(!dateList.contains(closingdate)){
			dateList.add(closingdate);
		}
		Collections.sort(dateList);
		List<Object> listdata = commonService.getIndexForWeb(Constants.matchId,Constants.QSN_ID);
		modelMap.put("opening", opendingdate);
		modelMap.put("closing", closingdate);
		modelMap.put("PXnum", getPXnum(dateList,15));
		modelMap.put("dateList", dateList);
		modelMap.put("listdata1", listdata.get(0));
		modelMap.put("listdata2", listdata.get(1));
		return new ModelAndView("index_qsn");
	}

	
	@RequestMapping("/qzty")
	@SuppressWarnings("all")
	public ModelAndView qzty(ModelMap modelMap){
		//获取竞赛的起止日期
		List<String> dateList = commonService.getDateList(Constants.matchId,Constants.QZTY_ID);
		if(!dateList.contains(opendingdate)){
			dateList.add(opendingdate);
		}
		if(!dateList.contains(closingdate)){
			dateList.add(closingdate);
		}
		Collections.sort(dateList);
		List<Object> listdata = commonService.getIndexForWeb(Constants.matchId,Constants.QZTY_ID);
		modelMap.put("opening", opendingdate); 
		modelMap.put("closing", closingdate); 
		modelMap.put("PXnum", getPXnum(dateList,17)); 
		modelMap.put("dateList", dateList);
		modelMap.put("listdata1", listdata.get(0));
		modelMap.put("listdata2", listdata.get(1));
		return new ModelAndView("index_qzty");
	}
	
	@RequestMapping("/shjlb")
	@SuppressWarnings("all")
	public ModelAndView shjlb(ModelMap modelMap){
		//获取竞赛的起止日期
		List<String> dateList = commonService.getDateList(Constants.matchId,Constants.SHJLB_ID);
		if(!dateList.contains(opendingdate)){
			dateList.add(opendingdate);
		}
		if(!dateList.contains(closingdate)){
			dateList.add(closingdate);
		}
		Collections.sort(dateList);
		List<Object> listdata = commonService.getIndexForWeb(Constants.matchId,Constants.SHJLB_ID);
		modelMap.put("opening", opendingdate); 
		modelMap.put("closing", closingdate); 
		modelMap.put("PXnum", getPXnum(dateList,17)); 
		modelMap.put("dateList", dateList);
		modelMap.put("listdata1", listdata.get(0));
		modelMap.put("listdata2", listdata.get(1));
		return new ModelAndView("index_shjlb");
	}
	@RequestMapping("/zdxs")
	@SuppressWarnings("all")
	public ModelAndView zdxs(HttpServletRequest request){

		return new ModelAndView("index_zdxs",model);
	}

	@RequestMapping("/zxs/{classId}")
	@SuppressWarnings("all")
	public ModelAndView zxs(@PathVariable Integer classId, HttpServletRequest request){
		model.put("classId",classId);
		return new ModelAndView("index_zxs",model);
	}
	@ResponseBody
	@RequestMapping("/getTimeFromColStu")
	public Map<String,Object> getTimeFromColStu(HttpServletRequest request){
		String tClass = request.getParameter("tClass");
		Map<Integer, List<String>> dateTime = matchService.getTimeFromColStu(tClass);
		System.err.println("dateTime = " + dateTime);
		model.put("dateTime",dateTime);
		return model;
	}
	
	public String getPXnum(List<String> dateList,int columns){ //column对应页面列 有17 和15两种值
		if(dateList.size()<=columns){ //少于columns列不做处理
			return "0";
		}
		Long days = 99999l;
		int leftNum = -1,rightNum=0;;
		String currentDate = DateUtil.getDay();
		for(String dateStr : dateList){
			Long diffDays = Math.abs(DateUtil.getDaySub(dateStr, currentDate));
			if(diffDays<days){
				days = diffDays;
				leftNum ++;
			}else{
				rightNum ++;
			}
		}
		if(rightNum-3<=0){//最近的日期右边本身不足3列
			return "0"; 
		}
		if(columns==17){
			int num = (rightNum - 3 - (leftNum>11?0:(12-leftNum)));
			if(num>0){
				return -num*53+"px";
			}
		}
		if(columns==15){
			int num = (rightNum - 3 - (leftNum>9?0:(10-leftNum)));
			if(num>0){
				return -num*53+"px";
			}
		}
		return "0";
	}
	
	
	/**************************************纪录**************************************************/
	//跳转记录---青少年
	@RequestMapping("/recordInfo/{order}")
	public ModelAndView recordInfo(HttpServletRequest request,@PathVariable String order,ModelMap modelMap){
		List<Map<String, Object>> map = null;
		HashMap<String, String> params = RequestParam.getQueryString(request);
		Integer pid = Integer.parseInt(params.get("pid"));
		try {
			map = commonService.getRecordFor(pid.toString(),order);  //根据pid过滤类别
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelMap.put("order", order);
		modelMap.put("map", map);
		modelMap.put("pid", pid);
		return new ModelAndView("recordInfo");
	}
	
	/**************************************每日成绩***************************************************/
	//跳转决赛成绩
	@RequestMapping("/dateInfo")
	public ModelAndView SingleDateInfo(HttpServletRequest request){
		HashMap<String, String> params = RequestParam.getQueryString(request);
		Integer pid = Integer.parseInt(params.get("pid"));
		String  day = params.get("day");		
		List<String> list = matchService.findTimes(pid);
		Map<Integer, List<String>> map = new LinkedHashMap<Integer, List<String>>();
		for (String s : list) {
			if(!StringUtils.isBlank(s)){
				String ts[] = s.split("-");
				if(map.containsKey(Integer.parseInt(ts[1]))){
					List<String> list1 = map.get(Integer.parseInt(ts[1]));
					list1.add(s);
				}else{
					List<String> list2 = new ArrayList<String>();
					list2.add(s);
					map.put(Integer.parseInt(ts[1]), list2);
				}
			}
		}
		Set<Map.Entry<Integer, List<String>>> entries = map.entrySet();
		Iterator<Map.Entry<Integer, List<String>>> iterator = entries.iterator();
		while (iterator.hasNext()){
			Map.Entry<Integer, List<String>> next = iterator.next();
			Object[] array = next.getValue().toArray();
			Arrays.sort(array, new Comparator<Object>() {
				@Override
				public int compare(Object o1, Object o2) {
					Integer c1 = Integer.parseInt(((String)o1).split("-")[2]);
					Integer c2 = Integer.parseInt(((String)o2).split("-")[2]);
					return c1-c2;
				}
			});

			List<String> newValue = new ArrayList<>();
			for (Object o : array) {
				newValue.add((String) o);
			}
			next.setValue(newValue);
		}

		model.put("map", map);
		model.put("pid", pid);
		model.put("day", day);
		return new ModelAndView("singleDateInfo",model);
	}
	@ResponseBody
	@RequestMapping(value = "/dataInfo", method = RequestMethod.POST)
	public ModelAndView dataInfo(Integer pid,String  day){
		List<Match> listP = matchService.findMatchByTime(day,pid);
		Map<Match,List<Match>> map = new LinkedHashMap<>();
		Integer count = 0;
		for (Match m : listP) {
			List<Match> listM = matchService.findMatchByParam(day,m.getCid());
			for(Match match : listM) {
				if("1".equals(match.getStatus())) {
					count++;
				}
			}
			map.put(m, listM);
		}
		model.put("map", map);
		model.put("listP", listP);
		model.put("day", day);
		model.put("count", count);
		return new ModelAndView("/template/dataInfo",model);
	}

	@ResponseBody
	@RequestMapping(value = "/dataInfoForCol", method = RequestMethod.POST)
	public ModelAndView dataInfoForCol(String time,String tClass){
		List<Match> listP = matchService.findMatchByTimeForzdxs(time,tClass);
		Map<Match,List<Match>> map = new LinkedHashMap<>();
		Integer count = 0;

		for (Match m : listP) {
			List<Match> listM = matchService.findMatchByParamForzdxs(time,m.getClassAllName());
			count+=listM.size();
			map.put(m, listM);
		}

		model.put("map", map);
		model.put("listP", listP);
		model.put("time", time);
		model.put("count", count);
		model.put("tClass", tClass);
		return new ModelAndView("/template/dataInfoForzdxs",model);
	}
	
	
	
	
	/**********************************************单项赛程***************************************************/
	/**
	 * 
	 * @Description: 跳转单项赛程页面
	 * @param groupStr
	 * @param pid
	 * @return ModelAndView
	 */
	@RequestMapping("/sportInfo")
	public ModelAndView SingleSportInfoDay(HttpServletRequest request){
		HashMap<String, String> params = RequestParam.getQueryString(request);
		String  groupStr = params.get("groupStr");
		Group group= JsonUtils.jsonToPojo(groupStr,Group.class);		
		String  day = params.get("day");
		String  typeName = params.get("typeName");
		Integer pid = Integer.parseInt(params.get("pid"));
		model = singleSport(group, pid);
		model.put("day", day);
		model.put("pid", pid);
		model.put("typeName", typeName);
		return new ModelAndView("singleSportInfo",model);
	}
	
	/**
	 * 
	 * @Description: 单项成绩中的嵌入页面
	 * @param groupStr
	 * @return ModelAndView
	 */
	@ResponseBody
	@RequestMapping(value = "/content", method = RequestMethod.POST)
	public ModelAndView SingleSportInfo(String groupStr,Integer fid,String type){
		Group group= JsonUtils.jsonToPojo(groupStr,Group.class);

		List<String> tList = matchService.findGroupTime(group.getCid(),fid,type);  //项目id   小项id或者项目组别id
		List<MatchGroup> matchGroupList = new ArrayList<>();
		List<Match> listM = matchService.findMatch(group.getCid(),fid,type);
		String pre = "";
		MatchGroup matchGroup = null;
		for (Match match : listM) {
			if(match.getDataDate()==null||match.getDataDate().length()<=5) {
				continue;
			}
			String key = match.getDataDate().substring(5);
			if(!key.equals(pre)){
				matchGroup = new MatchGroup();
				matchGroup.setDate(key);
				List<Match> list = new ArrayList<>();
				list.add(match);
				matchGroup.setMatchList(list);
				matchGroupList.add(matchGroup);
				pre = key;
			}else{
				matchGroup.getMatchList().add(match);
			}
		}
		Iterator<MatchGroup> iterator = matchGroupList.iterator();
		while (iterator.hasNext()){
			MatchGroup next = iterator.next();
			List<Match> value = next.getMatchList();
			Collections.sort(value, new Comparator<Match>() {
				@Override
				public int compare(Match o1, Match o2) {
					if(o1.getDataHour()==null || o2.getDataHour()==null){
						return 0;
					}
					return o1.getDataHour().compareTo(o2.getDataHour());
				}
			});
		}
		model.put("tList", tList);
		model.put("matchGroupList", matchGroupList);
		model.put("group", group);
		model.put("fid", fid);
		return new ModelAndView("/template/content",model);
	}
	
	public static void main(String[] args) {
		System.out.println("2021-09-19".substring(5));
	}
	/**********************************************每日赛程***************************************************/
	/**
	 * 
	 * @Description: 单项赛程的成绩信息
	 * @param groupStr
	 * @return ModelAndView
	 */
	@RequestMapping(value = "/matchInfo")
	public ModelAndView matchInfo(HttpServletRequest request){
		HashMap<String, String> params = RequestParam.getQueryString(request);
		Integer pid   = Integer.parseInt(params.get("pid"));     //大类id
		Integer hid   = Integer.parseInt(params.get("hid"));     //项目id
		String  day   = params.get("day");            //日期yyyy-MM-dd
		String  name  = params.get("name");
		String  resultType  = params.get("resultType");

		List<Scores> list = matchService.findMatchInfo(hid);   //比赛项目id
				
		model.put("scores", list);
		model.put("day", day.substring(5));
		model.put("name",name);
		model.put("resultType",resultType);
		model.put("pid", pid);
		return new ModelAndView("/singleScoreInfo",model);
	}

	@RequestMapping(value = "/matchInfoForzdxs/{classAllName}/{time}/{tClass}")
	public ModelAndView matchInfoForzdxs(@PathVariable String classAllName,@PathVariable String time,@PathVariable String tClass){

		List<Scores> list = matchService.findMatchInfoForzdxs(classAllName);
		model.put("scores", list);
		model.put("time", time.substring(5));
		model.put("name",classAllName);
		model.put("tClass",tClass);
		return new ModelAndView("/singleScoreInfoForzdxs",model);
	}

	/**
	 * 
	 * @Description: 某项目下的所有参赛运动员
	 * @param
	 * @return ModelAndView
	 */
	@RequestMapping(value = "/groupList")
	public ModelAndView groupList(HttpServletRequest request){
		HashMap<String, String> params = RequestParam.getQueryString(request);
		Group   group = JsonUtils.jsonToPojo(params.get("groupStr"),Group.class);
		Integer pid   = Integer.parseInt(params.get("pid"));
		
		List<Group> groups = matchService.findGroup(group.getCid());
		
		Map<String, Object> map = matchService.findPGroup(pid);
		for (Map.Entry<String, Object> entry : map.entrySet()) { 
			  model.put(entry.getKey(), entry.getValue());
		}
		model.put("groups", groups);
		model.put("group", group);
		Map<String, List<Match>> matchs = new LinkedHashMap<>();
		if(groups.size()!=0){
			boolean flag = false;
			for (Group g : groups) {
				if("E".equals(g.getType())) {
					flag = true;
					break;
				}
				List<Match> list = matchService.findProject(g.getCid());
				if(list.size()>0){
					matchs.put(g.getName(), list);
				}
			}
			if(flag) {
				List<Match> list = matchService.findProject(group.getCid());
				if(list.size()>0){
					matchs.put(group.getName(), list);
				}
			}
		}else{
			List<Match> list = matchService.findProject(group.getCid());
			if(list.size()>0){
				matchs.put(group.getName(), list);
			}
		}
		model.put("matchs", matchs);
		model.put("pid", pid);
		return new ModelAndView("/groupList",model);
	}
	
	/**
	 * 
	 * @Description: 加载运动员列表
	 * @param groupStr
	 * @return ModelAndView
	 */
	@ResponseBody
	@RequestMapping(value = "/athleteList", method = RequestMethod.POST)
	public ModelAndView athleteList(String groupStr){
		Group group= JsonUtils.jsonToPojo(groupStr,Group.class);
		
		List<AthleteInfo> list = matchService.findAthleteList(group.getCid());  //小项cid
		model.put("list", list);
		model.put("group", group);
		return new ModelAndView("/template/athlete",model);
	}
	/**
	 * 
	 * @Description: 运动员详情
	 * @param cid
	 * @return ModelAndView
	 */
	@RequestMapping(value = "/athleteBaseInfo")
	public ModelAndView athleteBaseInfo(HttpServletRequest request){
		HashMap<String, String> params = RequestParam.getQueryString(request);
		Integer cid   = Integer.parseInt(params.get("cid"));

		AthleteInfo bean = matchService.findAthleteInfo(cid);
		List<Map<String, Object>> matchList = matchService.findMatchByAthleteid(cid);
		List<Map<String, Object>> resultList = matchService.althleteResultInfo(cid);
		model.put("bean", bean);
		model.put("matchList", matchList);
		model.put("resultInfo", resultList);
		return new ModelAndView("/athleteBaseInfo",model);
	}
	
	
	private Map<Integer, List<String>> getGroupTime(List<Group> groups){
		Map<Integer, List<String>> map = new HashMap<>();
		for (Group group : groups) {
			List<String> findGroupTime = matchService.findGroupTime(group.getCid(),null,null);
			map.put(group.getCid(), findGroupTime);
		}
		return map;
	}
	
	private Map<String, Object> singleSport(Group group,Integer pid){
		List<Group> groups = matchService.findGroup(group.getCid());
		Map<String, Object> map = matchService.findPGroup(pid);		
		for (Map.Entry<String, Object> entry : map.entrySet()) { 
			  model.put(entry.getKey(), entry.getValue());
		}
		model.put("groups", groups);
		model.put("group", group);
		return model;
	}
	
	/**************************************奖牌榜*****************************************/
	@RequestMapping("/reportInfo/{group}")
	public ModelAndView reportInfo(HttpServletRequest request,@PathVariable Integer group,ModelMap modelMap) {
		HashMap<String, String> params = RequestParam.getQueryString(request);
		Integer pid = Integer.parseInt(params.get("pid"));
		Integer queryId = pid;
		if (pid==12 && group == 1) {
			queryId = 14;
		}

		try {
			List<Map<String, Object>> list = commonService.queryReportInfo(queryId);
			model.put("map", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("type", group);
		model.put("pid",pid);
		return new ModelAndView("/reportInfo",model);
	}

	@RequestMapping("/reportInfo/query12WithAccountType")
	@ResponseBody
	public List<ThreeMetaData> query12WithAccountType(){
		try {

			List<ThreeMetaData> map = matchService.query12WithAccountType();
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/reportInfo/queryTeenagersThreeList/{pid}")
	@ResponseBody
	public List<FindOrderVO> queryTeenagersThreeList(@PathVariable Integer pid,Integer account){

		System.err.println("account = " + account);
		try {
			if (pid == 13) {
				List<FindOrderVO> data = matchService.queryTeenagersThreeList(pid,account);
				return data;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/reportInfoForzdxs/{type}")//zdxs , zxs
	public ModelAndView reportInfoForzdxs(@PathVariable String type) {
		model.clear();
		if(type!=null && type.equals("zxs")){
			model.put("type","中学生");
		}else{
			model.put("type","大学生");

		}
		return new ModelAndView("reportInfoForzdxs",model);
	}

	@RequestMapping("/getRankingByTClass/{tClass}")
	@ResponseBody
	public List<Map<String, Object>> getRankingByTClass(@PathVariable String tClass){
		return commonService.getRankingByTClass(tClass);
	}

	@RequestMapping("/getMedalDetailForzdxs/{unit}/{type}")
	@ResponseBody
	public ModelAndView getMedalDetailForzdxs(@PathVariable String unit,@PathVariable Integer type){
		List<Map<String,Object>> list = commonService.getMedalDetailForzdxs(unit,type);
		model.put("list", list);
		model.put("unit", unit);
		return new ModelAndView("/medalDetailForzdxs",model);
	}
	
	@RequestMapping("/reportInfo/detail/{type}")
	public ModelAndView toReportDetail(HttpServletRequest request,@PathVariable Integer type,ModelMap modelMap) {
		HashMap<String, String> params = RequestParam.getQueryString(request);
		Integer uid = Integer.parseInt(params.get("uid"));
		String uName = params.get("uname");
		Integer pid = Integer.parseInt(params.get("pid"));

		List<Map<String, Object>> list;
		try {
			list = commonService.queryReportDetail(uid, type,pid);
			model.put("detailList", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("unitName", uName);
		return new ModelAndView("/medalDetail",model);
	}

}
